package com.guimin.fuwu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guimin.common.util.SnowflakeIdWorker;
import com.guimin.common.util.exception.BaseException;
import com.guimin.common.vo.R;
import com.guimin.fuwu.dao.GuiminServiceDao;
import com.guimin.fuwu.entity.GuiminService;
import com.guimin.fuwu.service.GuiminServiceService;
import com.guimin.fuwu.vo.serveListVo;
import org.apache.logging.log4j.util.Base64Util;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;

/**
 * (GuiminService)表服务实现类
 *
 * @author makejava
 * @since 2021-11-17 10:13:06
 */
@Service
public class GuiminServiceServiceImpl extends ServiceImpl<GuiminServiceDao, GuiminService> implements GuiminServiceService {
    @Resource
    private GuiminServiceDao guiminServiceDao;

    /**
     * 雪花id生成器
     */
    private SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(0, 0);
    private static final long START_TIMESTAMP = 1625068800000L;
    /**
     * 生成订单id
     *
     * @return 订单id
     */
    public synchronized long nextId() {
        return snowflakeIdWorker.nextId(START_TIMESTAMP);
    }

    public static void main(String[] args) {
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(1625068800000L)));
    }

    /**
     * 添加分类
     * @param id
     * @param service
     * @return
     */
    public R<?> addServe(Long id, GuiminService service) {
        try {
            GuiminService gm = new GuiminService();
            BeanUtils.copyProperties(service,gm);
            gm.setId(nextId());
            gm.setUserId(id);
            gm.setCreateDatetime(new Date());

            QueryWrapper<GuiminService> wrapper = new QueryWrapper<>();
            wrapper.eq("name",service.getName());
            Integer integer = guiminServiceDao.selectCount(wrapper);
            if(integer != 0){
                return R.fail("该类名称已存在");
            }

            int insert = guiminServiceDao.insert(gm);
            if(insert>0){
                return R.success("添加类别成功");
            }else {
                return R.fail("添加类别失败");
            }
        }catch (Exception e){
            e.printStackTrace();//打印异常
            throw new BaseException("网络错误，添加失败");
        }
    }

    /**
     * 添加服务类别
     * @param id
     * @param service
     * @return
     */
    public R<?> addServeType(Long id, GuiminService service) {
        try {
            GuiminService fuWu = new GuiminService();
            BeanUtils.copyProperties(service,fuWu);
            fuWu.setId(nextId());
            fuWu.setUserId(id);
            fuWu.setCreateDatetime(new Date());
            System.out.println("要添加的参数："+fuWu);

            QueryWrapper<GuiminService> wrapper = new QueryWrapper<>();
            wrapper.eq("name",service.getName());
            Integer integer = guiminServiceDao.selectCount(wrapper);
            if(integer != 0){
                return R.fail("该类名称已存在");
            }

            int insert = guiminServiceDao.insert(fuWu);
            if(insert>0){
                return R.success("添加服务成功");
            }else {
                return R.fail("添加服务失败");
            }
        }catch (Exception e){
            e.printStackTrace();//打印异常
            throw new BaseException("网络错误，添加失败");
        }
    }

    public String getBaseImg(String imgPath){

        if (imgPath==null || imgPath.equals("")){
            return null;
        }
        File file = new File(imgPath);
        if (!file.exists()){
            throw new BaseException("头像文件不存在");
        }else if (file.isDirectory()){
            throw new BaseException("头像文件不存在");
        }

        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream( imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (data==null){
            throw new BaseException("头像不存在");
        }
        return Base64.getEncoder().encodeToString(data);
    }

    /**
     * 获取服务列表
     * @param id
     * @return
     */
    public List<GuiminService> getServeList(Long id) {
        try {
            if(id == null){
                throw new BaseException("用户未登录");
            }
            QueryWrapper<GuiminService> gm = new QueryWrapper<>();
            gm.eq("user_id",id);
            List<GuiminService> list = guiminServiceDao.selectList(gm);
            ArrayList<GuiminService> list2 = new ArrayList<>();
           //把图片路径进行转码
            for (GuiminService i : list){
                GuiminService service = new GuiminService();
                String imgPath = i.getImgPath();
                String baseImg = this.getBaseImg(imgPath);
                BeanUtils.copyProperties(i,service);
                service.setImgPath(baseImg);
                list2.add(service);
            }
            if(list2.size() != 0){
                return list2;
            }else {
                return null;
            }
        }catch (Exception e){
            throw new BaseException("请求数据异常");
        }

    }

    /**
     * 获取服务列表2
     * @param id
     * @return
     */
    public ArrayList<serveListVo> getServeListF(Long id) {
        try {
            QueryWrapper<GuiminService> gm = new QueryWrapper<>();
            gm.eq("user_id",id);
            List<GuiminService> list = guiminServiceDao.selectList(gm);
            ArrayList<serveListVo> listVos = new ArrayList<>();
            for (GuiminService service : list){
                serveListVo serveListVo = new serveListVo();
                BeanUtils.copyProperties(service,serveListVo);
                //base64转码
                String baseImg = this.getBaseImg(service.getImgPath());
                serveListVo.setImgPath(baseImg);//编码过
                serveListVo.setNotBase64ImgPath(service.getImgPath());//未编码
                serveListVo.setFreeDate("请选择免费日");
                listVos.add(serveListVo);
            }
            if(list.size() != 0){
                return listVos;
            }else {
                return null;
            }
        }catch (Exception e){
            throw new BaseException("请求数据异常");
        }

    }

    /**
     * 通过id修改数据
     * @param id
     * @param service
     * @return
     */
    public R<?> alterServe(Long id, GuiminService service) {
        try {
            if(id == null){
                throw new BaseException("id为空");
            }
            if(service == null){
                throw new BaseException("请求参数为空");
            }
            service.setUpdateDatetime(new Date());
            QueryWrapper<GuiminService> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",id);
            wrapper.eq("id",service.getId());
            int update = guiminServiceDao.update(service, wrapper);
            if(update > 0){
                return R.success("修改成功");
            }else {
                return  R.fail("修改失败");
            }
        }catch (Exception e){
            throw new BaseException("网络错误");
        }

    }

    /**
     * 通过id删除
     * @param userid
     * @param id
     * @return
     */
    public R<?> deleteServe(Long userid, Long id) {
        try {
            if(userid == null || id == null){
                throw new BaseException("请求参数为空");
            }
            int i = guiminServiceDao.deleteById(id);
            if(i > 0){
                return R.success("删除成功");
            }else {
                return  R.fail("删除失败");
            }
        }catch (Exception e){
            throw new BaseException("网络错误");
        }
    }
}
